<template>
  <div style="height: 100%;">
    <el-row :gutter="20" style="margin-left:0px;margin-right:0px;height: 100%;">
      <el-col :span="6" style="padding:0px;  height: 100%; border-right: 1px solid#ccc;">
        <!-- 组织机构树 -->
        <div class="zztree ">
          <div slot="header" class="clearfix zztree-title">
            <span class="span-title">组织机构树</span>
          </div>
          <div class="zztree-con tree-detail" style="height: 100%;overflow-y: auto;">
            <el-tree ref='tree'
               :data="treeData"
               v-loading="loading"
               :props="defaultProps"
               :expand-on-click-node='false'
               @node-click="handleNodeClick"
               node-key="id"
               :highlight-current='true'
               :default-expand-all='true'>
                  <span class="custom-tree-node" slot-scope="{ node, data }">
                    <span v-if="data.other.Status == 0" class="ztrrName" style="display: inline-block;" :title="data.name">{{ data.name }}</span>
                    <span v-if="data.other.Status == 1" class="ztrrName" style="display: inline-block;color:red" :title="data.name">{{ data.name }}(禁用)</span>

                   </span>
               </el-tree>
          </div>
        </div>
      </el-col>
      <el-col :span="18" style="padding:0px;height: 100%;">
        <div class="job-tab">
          <div slot="header" class="clearfix zztree-title">
            <span class="span-title">角色列表</span>
          </div>
          <div style="margin-top:15px;">
            <div class="select-container">
              <el-row class="">
                <el-col :span="24" class="">
                  <el-form ref="form" label-width="100px" label-position='right' size="small" :inline="true">
                  <el-col :span="5" >
                      <el-form-item label="" prop="name" size='small'  style="margin:12px 5px;">
                          <el-input prefix-icon="el-icon-search" placeholder="角色名称" v-model="listQueryDemo.condition.name.value" clearable></el-input>
                      </el-form-item>
                  </el-col>
                  <el-col :span="5" >
                      <el-form-item label="" prop="subsysid" size='small' style="margin:12px 5px;">
                          <el-select placeholder="请选择子系统"  v-model="listQueryDemo.condition.subsysid.value" clearable @focus="editSubSystemsOptions">
                              <el-option v-for="item in subSystemsOptions" :key="item.id" :label="item.name" :value="item.id">
                              </el-option>
                          </el-select>
                      </el-form-item>
                  </el-col>
                  <el-col :span="4" >
                    <!-- 角色状态 -->
                      <el-form-item label="" prop="status" size='small' style="margin:12px 5px;">
                          <el-select placeholder="请选择角色状态" v-model="listQueryDemo.condition.status.value" clearable>
                              <el-option v-for="item in statusOptions" :key="item.key" :label="item.display_name" :value="item.key">
                              </el-option>
                          </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="10" style="padding-left:3px;margin-top:12px;float:right;margin-right:0">
                      <el-button size="small" style="height:30px;padding-top:0px;line-height:30px;" type="success" icon="el-icon-edit" @click="getTree('find')">查 询</el-button>
                      <el-button size="small" style="height:30px;padding-top:0px;line-height:30px;" type="danger" icon="el-icon-circle-close-outline" @click="handleResetOrg()">重 置</el-button>
                      <el-button size="small" style="height:30px;padding-top:0px;line-height:30px;" type="primary" icon="el-icon-circle-plus-outline" @click="handleCreate">新建</el-button>
                    </el-col>
                  </el-form>
                </el-col>
              </el-row>
            </div>
          </div>
        </div>
        <div class="job-table">
          <el-table
            :data="userDataDemo"
            size="small"
            height="370px"
            style="width: 100%;overflow: auto;border:#eeeeee">
            <el-table-column
              width="30" align="center" >
            </el-table-column>
            <el-table-column type="index" label="序号" width="50" align="center">
              <template slot-scope="scope">
              <span>{{scope.$index + (serialNumberOrg - 1) * listQueryDemo.rowBounds.limit + 1}}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              label="角色名"
              width="150px" align="center" >
            </el-table-column>
            <el-table-column
              prop="subsysname"
              label="子系统名称"
              width="150px" align="center" >
            </el-table-column>
            <el-table-column
              label="角色状态" width="120px" align="center" >
              <template slot-scope="scope">
                {{scope.row.status | statusFilter}}
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center" >
              <template slot-scope="scope">
                <el-button style="margin-left:5px;" type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button style="margin-left:5px;" type="text" size="small" @click="handleDelete(scope.row,'delete')">删除</el-button>
                <el-button style="margin-left:5px;" type="text" size="small" @click="handleEditJob(scope.row)">配置人员</el-button>
                <el-button style="margin-left:5px;" type="text" size="small" @click="handleEditRole(scope.row)">配置权限</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <el-pagination background @size-change="handleSizeChangeDemo"
                           @current-change="handleCurrentChangeDemo"
                           :page-sizes="[10,20,30, 50]"
                           :page-size="listQueryDemo.rowBounds.limit"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="totalDemo">
            </el-pagination>
          </div>
        </div>
      </el-col>
    </el-row>
    <!--新建角色弹出层-->
    <el-dialog
      v-if="dialogVisibleAddRole"
      :close-on-click-modal="false"
      title="创建角色"
      :visible.sync="dialogVisibleAddRole"
      width="70%">
      <newRole :newOrgData="newOrgData" @changeCloseDialog="changeCloseDialog"></newRole>
    </el-dialog>
    <!--编辑角色弹出层-->
    <el-dialog
      v-if="dialogVisibleEditRole"
      :close-on-click-modal="false"
      title="编辑角色"
      :visible.sync="dialogVisibleEditRole"
      width="70%">
      <editRole :roleFormData="roleFormData" @changeCloseDialog="changeCloseDialog"></editRole>
    </el-dialog>
    <!--配置人员弹出层-->
    <el-dialog
      v-if="dialogVisibleEditJob"
      :close-on-click-modal="false"
      title="配置人员"
      :visible.sync="dialogVisibleEditJob"
      width="70%">
      <editRoleUser :editJob="editJob" @changeCloseDialog="changeCloseDialog"></editRoleUser>
    </el-dialog>
    <!--配置权限弹出层-->
    <el-dialog
      v-if="dialogVisiblePowerRole"
      :close-on-click-modal="false"
      title="配置权限"
      :visible.sync="dialogVisiblePowerRole"
      width="70%">
      <powerRole :powerRoleData="powerRoleData" @changeCloseDialog="changeCloseDialog"></powerRole>
    </el-dialog>
  </div>
</template>

<script>
import {
  SelectUserRoleByOrgId,
  SysOrgInfo,
  treeById
} from '@/api/systemManage/roleManagementRoleEdit'
import {
  forceDeleteItem,
  selectSysSubsys,
  SelectRoleAndSubSys
} from '@/api/systemManage/roleManagement'
import {
  statusOptions,
  statusKeyValue,
  ptOptions,
  ptKeyValue
} from '@/utils/allOptions'

import newRole from './newRole'
import editRole from './editRole'
import editRoleUser from '@/views/systemManage/roleManagement/editRoleUser'
import powerRole from '@/views/systemManage/roleManagement/powerRole'

export default {
  components: {
    newRole,
    editRole,
    editRoleUser,
    powerRole
  },
  data() {
    return {
      dialogVisibleAddRole: false,
      dialogVisibleEditRole: false,
      dialogVisibleEditJob: false,
      dialogVisiblePowerRole: false,
      roleFormData: {},
      editJob: {},
      powerRoleData: {},
      newOrgData: [],
      total: 0,
      treeData: [],
      loading: false,
      subSystemsOptions: [],
      userDataDemo: [],
      statusOptions,
      ptOptions,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      listQueryDemo: {
        rowBounds: {
          offset: 0,
          limit: 10
        },
        condition: {
          name:{
            property: 'name',
            value: '',
            type: 'LIKE'
          },
          status: {
            property: 'status',
            value: '0',
            type: 'EQ'
          },
          subsysid:{
            'property': 'subsysid',
            'value': '',
            'type': 'EQ'
          },
          orgId: {
            property: 'orgId',
            value: '',
            type: 'EQ'
          }
        },
        fields: [
        ],
        sort: [{
          direction: 'ASC',
          property: 'id'
        }]
      },
      totalDemo: 0,
      serialNumberOrg: 1
    }
  },
  // 画面刚进入method
  mounted() {
    this.editSubSystemsOptions()
  },
  created() {
    this.getTree()
  },
  filters: {
    statusFilter(target) {
      return statusKeyValue[target]
    },
    ptFilter(target) {
      return ptKeyValue[target]
    }
  },
  methods: {
    changeCloseDialog() {
      this.dialogVisibleAddRole = false
      this.dialogVisibleEditRole = false
      this.dialogVisibleEditJob = false
      this.dialogVisiblePowerRole = false
      this.getTree()
    },
    handleEdit(row) {
      this.roleFormData = row
      this.dialogVisibleEditRole = true
    },
    handleEditJob(row) {
      this.editJob = row
      this.dialogVisibleEditJob = true
    },
    handleEditRole(row) {
      this.powerRoleData = row
      this.dialogVisiblePowerRole = true
    },
    handleDelete(row, flag) {
      this.$confirm(
        '此操作将删除【' + row.name + '】, 是否继续?',
        '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          const data = {
            'id': row.id
          }
          forceDeleteItem(data).then(response => {
            this.$nextTick(() => {
              this.$refs.treeRef.setCurrentKey(this.$store.state.user.selectRoleOrgIdByRoleOrg) // treeBox 元素的ref   value 绑定的node-key
            })
            this.$message({
              message: '【' + row.name + '】已经被删除。',
              type: 'success'
            })
            // this.handleReset()
            this.getTree(flag)
          })
        })
        .catch(error => {
          console.error(error)
        })
    },
    handleCreate() {
       this.dialogVisibleAddRole = true
    },
    handleUserRole(row) {
      this.dialogVisibleEditUserRole = true
    },
    // 翻页器使用(按组织机构添加人员)
    handleSizeChangeDemo(val) {
      this.listQueryDemo.rowBounds.limit = val
      this.listQueryDemo.rowBounds.offset = this.listQueryDemo.rowBounds.limit * (this.serialNumberOrg - 1)
      this.selectUserByOrgId()
    },
    // 翻页器使用(按组织机构添加人员)
    handleCurrentChangeDemo(val) {
      this.serialNumberOrg = val
      this.listQueryDemo.rowBounds.offset =
      this.listQueryDemo.rowBounds.limit * (val - 1)
      this.selectUserByOrgId()
    },
     selectUserByOrgId() {
        SelectRoleAndSubSys(this.listQueryDemo).then(response => {
          this.userDataDemo = response.data.data.records
          this.totalDemo = response.data.data.count
        })
     },
    getTree(flag) {
      this.listLoading = true
      if (flag === 'find') {
        this.listQueryDemo.rowBounds.offset = 0
        this.serialNumberOrg = 1
        this.totalDemo = 0
      }
      if (flag ==='delete') {
        if (this.listQueryDemo.rowBounds.offset == (this.totalDemo - 1)
         && this.listQueryDemo.rowBounds.offset >= this.listQueryDemo.rowBounds.limit) {
          this.listQueryDemo.rowBounds.offset -=this.listQueryDemo.rowBounds.limit
          this.serialNumberOrg -=1
        }
      }

      treeById({ id: this.$store.getters.orgId }).then(response => {
        this.treeData = response.data.data
        if (this.$store.state.user.selectRoleOrgIdByRoleOrg) {
            this.$nextTick(() => {
              this.$refs.tree.setCurrentKey(this.$store.state.user.selectRoleOrgIdByRoleOrg) // treeBox 元素的ref   value 绑定的node-key
            })
            this.listQueryDemo.condition.orgId.value = this.$store.state.user.selectRoleOrgIdByRoleOrg
            this.newOrgData.orgId = this.$store.state.user.selectRoleOrgIdByRoleOrg
         } else {
            this.$nextTick(() => {
              this.$refs.tree.setCurrentKey(this.$store.state.user.selectOuinfoId) // treeBox 元素的ref   value 绑定的node-key
            })
            this.listQueryDemo.condition.orgId.value = this.$store.state.user.selectOuinfoId
            this.newOrgData.orgId = this.$store.state.user.selectOuinfoId
         }
         this.selectUserByOrgId()
      })
    },
     selectionOrgChange(val,row) {
     },
    closeSelf() {
      this.$emit('changeCloseDialog')
    },
    editSubSystemsOptions() {
      const query = {
        sort: [
          {
            direction: 'ASC',
            property: 'id'
          }
        ]
      }
      selectSysSubsys(query).then(response => {
        const records = response.data.data.records
        if (response.data.data.count > 0) {
          this.subSystemsOptions = []
          for (const item of records) {
            const input = {}
            input.id = item.id
            input.name = item.name
            this.subSystemsOptions.push(input)
          }
        }
      })
    },

    handleNodeClick(data) {
      this.serialNumberOrg =1
      this.listQueryDemo.rowBounds.offset =0
      this.totalDemo =0
      this.listQueryDemo.condition.orgId.value = data.id
      this.$store.commit('SET_SELECTROLEORGID_BYROLEORGID', data.id)
      this.newOrgData.orgId = data.id
      this.newOrgData.orgName = data.name
      this.selectUserByOrgId()
    },
     handleResetOrg() {
       this.listQueryDemo.condition.name.value = ''
       this.listQueryDemo.condition.subsysid.value = ''
       this.listQueryDemo.condition.status.value = '0'
       this.listQueryDemo.rowBounds.offset = 0
       this.listQueryDemo.rowBounds.limit = 10
       this.totalDemo = 0
       this.serialNumberOrg = 1
       this.selectUserByOrgId()
     }
  }
}
</script>

<style scoped>
.treeArea {
    max-height: 66vh;
    overflow-y: auto;
}
</style>
